package com.taotao.thread.Test1;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjin
 * @title: T09_Testphaser2
 * @projectName thread
 * @description: TODO
 * @date 2022/5/4 0004 11:02
 */
public class T09_Testphaser2 {
    static Random random = new Random();
    static MarriagePhaser phaser = new MarriagePhaser();

    static void millisleep(int milli) {
        try {
            TimeUnit.MICROSECONDS.sleep(milli);
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public static void main(String[] args) {
        phaser.bulkRegister(7);
        for (int i = 0; i < 5; i++) {
            new Thread(new Person("p" + i)).start();
        }
        new Thread(new Person("新郎")).start();
        new Thread(new Person("新娘")).start();
    }

    static class MarriagePhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0:
                    System.out.println("所有人都到齐了！" + registeredParties);
                    System.out.println();
                    return false;
                case 1:
                    System.out.println("所有人都吃完了！" + registeredParties);
                    System.out.println();
                    return false;

                case 2:
                    System.out.println("所有人都离开了！" + registeredParties);
                    System.out.println();
                    return false;
                case 3:
                    System.out.println("婚礼结束！送入洞房");
                    return true;
                default:
                    return true;
            }
        }

        ;
    }

    static class Person implements Runnable {
        String name;

        public Person(String name) {
            this.name = name;
        }

        public void arrive() {
            millisleep(random.nextInt(1000));
            System.out.println("%s 到达现场! \n"+name);
            phaser.arriveAndAwaitAdvance();
        }
        public void eat(){
            millisleep(random.nextInt(1000));
            System.out.println("%s 吃完! \n"+name);
            phaser.arriveAndAwaitAdvance();
        }
        public void leave(){
            millisleep(random.nextInt(1000));
            System.out.println("%s 离开! \n"+name);
            phaser.arriveAndAwaitAdvance();
        }
        public void hunger(){
            if(name.equals("新郎") || name.equals("新娘")){
                millisleep(random.nextInt(1000));
                System.out.println("%s 送入洞房! \n"+name);
                phaser.arriveAndAwaitAdvance();
            }else {
                phaser.arriveAndDeregister();
            }
        }
        @Override
        public void run() {
            arrive();
            eat();
            leave();
            hunger();
        }
    }
}
